import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input, Select } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import SelectForm from '@/components/SelectForm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import AntdFormItem from '@/components/AntdFormItem';
import AntdForm from '@/components/AntdForm';
import FileImport from '@/components/FileImport';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import FileReader from '@/components/FileReader';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import { queryDict, filterAddFile, filterDeteteFile } from '@/utils/common';
import prompt from '@/components/Prompt';
import {
  allDispatchType,
  codes,
  trailNodeStatus,
  trailType,
  statusAndType,
  formatStatusAndType,
  selectEvents,
} from './utils';
import styles from './trailUpdate.less';

const { confirm } = Modal;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD HH:mm';
const dateFormatS = 'YYYY-MM-DD HH:mm:ss';

@ManageList
@connect(({ trailUpdate, loading, component }) => ({
  trailUpdate,
  trailUpdateList: trailUpdate.trailUpdateList,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class TrailUpdate extends Component {
  constructor(props) {
    super(props);
    const {
      form: { getFieldDecorator },
    } = props;
    this.commonParams = {
      getFieldDecorator,
    };
    this.state = {
      selectedRows: [],
      disabled: false,
      visibleFile: false,
      orderNum: '',
      orderId: '',
      showTips: '',
      eventList: {},
      typeList: [],
    };
  }
  className = 'trailupdateInfo-table';
  columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      width: 130,
      render: (text, record) => {
        const { disabled } = this.props;
        const { orderNum } = this.state;
        if (!orderNum) {
          return (
            <AntdFormItem
              label=" "
              code={`orderNo-${record.id}`}
              initialValue={text}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput
                value={text}
                disabled={disabled}
                onChange={value => this.handleFieldChange(value, 'orderNo', record.id)}
              />
            </AntdFormItem>
          );
        }
        return text;
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 120,
      render: (text, record) => {
        const { disabled, typeList, eventList } = this.state;
        const {
          dictObject,
          form: { getFieldDecorator },
        } = this.props;
        return (
          <AntdFormItem
            label=" "
            code={`type-${record.id}`}
            initialValue={text}
            {...this.commonParams}
            rules={[{ required: true }]}
          >
            <AdSelect
              disabled={disabled}
              isExist={true}
              data={typeList}
              onChange={value => this.handleFieldChange(value, 'type', record.id, 'status')}
            />
          </AntdFormItem>
        );
      },
    },
    {
      title: '节点状态',
      dataIndex: 'status',
      width: 120,
      render: (text, record) => {
        const { disabled } = this.state;
        const { dictObject } = this.props;
        return (
          <AntdFormItem
            label=" "
            code={`status-${record.id}`}
            initialValue={text}
            {...this.commonParams}
            rules={[{ required: true }]}
          >
            <AdSelect
              disabled={disabled}
              isExist={true}
              //   data={trailNodeStatus}
              data={record.statusList || []}
              show={{ id: 'status', name: 'status' }}
              onChange={value => this.handleFieldChange(value, 'status', record.id, 'type')}
            />
          </AntdFormItem>
        );
      },
    },
    {
      title: '时间',
      dataIndex: 'eventTime',
      width: 220,
      render: (text, record) => {
        const { disabled } = this.state;
        return (
          <AntdFormItem
            label=" "
            code={`eventTime-${record.id}`}
            initialValue={text ? moment(text, dateFormat) : null}
            {...this.commonParams}
            rules={[{ required: true }]}
          >
            <AntdDatePicker
              showTime
              disabled={disabled}
              onChange={value => this.handleFieldChange(value, 'eventTime', record.id)}
            />
          </AntdFormItem>
        );
      },
    },
    {
      title: '节点描述',
      dataIndex: 'eventDesc',
      width: 220,
      render: (text, record) => {
        const { disabled } = this.props;
        return (
          <AntdFormItem
            label=" "
            code={`eventDesc-${record.id}`}
            initialValue={text}
            {...this.commonParams}
          >
            <AntdInput
              type="textarea"
              value={text}
              rows={1}
              disabled={disabled}
              onChange={value => this.handleFieldChange(value, 'eventDesc', record.id)}
            />
          </AntdFormItem>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      width: 220,
      render: (text, record) => {
        const { disabled } = this.props;
        return (
          <AntdFormItem
            label=" "
            code={`remarks-${record.id}`}
            initialValue={text}
            {...this.commonParams}
          >
            <AntdInput
              type="textarea"
              value={text}
              rows={1}
              disabled={disabled}
              onChange={value => this.handleFieldChange(value, 'remarks', record.id)}
            />
          </AntdFormItem>
        );
      },
    },
    {
      title: '附件',
      dataIndex: 'fileTokens', // 表单提交：fileTokens  列表返回：trackFiles
      // width: 80,
      render: (text, record) => {
        const { disabled } = this.state;
        return (
          <AntdFormItem
            label=" "
            code={`fileTokens-${record.id}`}
            initialValue={record.fileList || []}
            {...this.commonParams}
          >
            <FileReader
              urlType=""
              actionNameUrl="filesystem/file-manager/uploadFile?appId=001&isTemp =true"
              cusDownloadUrl=""
              readNameUrl=""
              onChange={value => this.handleFieldChange(value, 'fileTokens', record.id)}
              disabled={disabled}
              hasCompleteUrl={true}
            />
          </AntdFormItem>
        );
      },
    },
  ];

  componentWillMount() {
    // 查询字典项
    // const allDict = [allDictList.trailNodeStatus];
    // queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const { orderNum, getTrailUpdateList, onRef } = this.props;
    onRef && onRef(this);
    const id = orderNum;
    this.selectEvents();
    if (!id) return;
    this.handleStateChange([{ detailId: id }]);
    const detail = getTrailUpdateList[id];
    this.getTrailUpdateList(id);
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { orderNo, getTrailUpdateList, renderNeed } = nextProps;
    const { orderNum } = nextState;

    if (this.props.orderNo !== orderNo) {
      this.handleStateChange([{ orderNum: orderNo }]);
      this.getTrailUpdateList({ orderNo });
    }
  }

  //类型-->节点状态：(联动)
  selectEvents = () => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.selectEvents,
      payload: {},
      callback: res => {
        let newArr = [];
        if (res && Object.keys(res).length > 0) {
          for (let k in res) {
            newArr.push({ value: k, code: k });
          }
        }
        this.setState({
          eventList: res || {},
          typeList: newArr || [],
        });
      },
    });
  };

  getTrailUpdateList = (params, callback) => {
    const { dispatch, checkOrder } = this.props;
    const { eventList } = this.state;
    dispatch({
      type: allDispatchType.list,
      payload: params,
      callback: res => {
        if (res.code !== 0) {
          this.setState({
            orderNum: '',
            orderId: '',
          });
          checkOrder({ existOrders: false });
          return;
        }

        let newData = res.data;
        this.setState({
          orderId: newData[0].orderId,
        });
        checkOrder({ existOrders: true });
        newData.map(v => {
          v.statusList = eventList[v.type];
          if (v.trackFiles && v.trackFiles.length > 0) {
            v.fileList = [];
            let obj = {};
            v.trackFiles.map(t => {
              obj = {
                fileName: t.fileName || t.fileType || '',
                fileToken: t.id,
                fileType: t.fileType || '',
                id: t.id,
                fileUrl: t.fileUrl,
              };
              v.fileList.push(obj);
            });
          } else {
            v.fileList = [];
          }
        });
        this.saveAllValue({
          trailUpdateList: { [this.state.orderNum]: { list: newData } },
        });
      },
    });
  };

  getAddDataObj = () => {
    return {
      id: `isNew${Math.ceil(Math.random() * 10000) + 10000}`,
      orderNo: this.state.orderNum,
      orderId: this.state.orderId,
      eventCode: '',
      type: '',
      status: '',
      eventTime: '',
      eventDesc: '',
      remarks: '',
      fileTokens: [],
    };
  };
  //新增
  handleAdd = () => {
    const { orderNum } = this.state;
    let newData = this.getInfoData();
    newData = [this.getAddDataObj(), ...newData];
    this.saveAllValue({ trailUpdateList: { [orderNum]: { list: newData } } });
  };

  getInfoData = () => {
    const { trailUpdateList } = this.props;
    const { orderNum } = this.state;
    let newData = [];
    if (trailUpdateList[orderNum]) {
      const data = trailUpdateList[orderNum].list;
      newData = data.map(item => ({ ...item }));
    }
    return newData;
  };

  getRowByKey(id, newData) {
    const data = this.getInfoData();
    return (newData || data).filter(item => item.id === id)[0];
  }

  handleFieldChange(value, fieldName, id, fieldName2) {
    // console.log('value, fieldName, id, fieldName2', value, fieldName, id, fieldName2);

    const { orderNum, eventList } = this.state;
    const { dispatch, showTipsFun, form } = this.props;
    showTipsFun(true);
    const newData = this.getInfoData();
    const target = this.getRowByKey(id, newData);
    if (target) {
      target[fieldName] = value;
    }
    if (fieldName === 'eventTime') {
      if (value) {
        target.eventTime = moment(value).format(dateFormatS);
      }
    } else if (fieldName === 'fileTokens') {
      target.fileTokens = filterAddFile(value) || [];
      target.delIds = filterDeteteFile(value, target.fileList || []) || []; //测试
    }
    //状态-->类型（联动）
    if (fieldName == 'type') {
      target.statusList = eventList[value];
      form.setFieldsValue({ [`${fieldName2}-${target.id}`]: null });
      target[fieldName2] = '';
      target.eventCode = '';
    }
    if (fieldName == 'status') {
      target.statusList.map(v => {
        if (v.status == value) {
          target.eventCode = v.code;
        }
      });
      target.eventDesc = value;
      form.setFieldsValue({ [`eventDesc-${target.id}`]: value });
    }
    // console.log('target:', target);

    this.saveAllValue({ trailUpdateList: { [orderNum]: { list: newData } } });
  }
  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };
  /* 表格表单数据处理---end---*/

  //保存：
  saveData = () => {
    const { form, trailUpdateList, dispatch, showTipsFun } = this.props;
    const { orderNum } = this.state;
    const orderNo = orderNum;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      let params = trailUpdateList[orderNum].list;
      if (params && params.length > 0) {
        params = params.map(item => {
          const { fileList, trackFiles, statusList, ...restd } = item;
          if (item.id.includes('isNew')) {
            const { id, ...rest } = restd;
            return rest;
          }
          return restd;
        });
      }
      dispatch({
        type: allDispatchType.save,
        payload: params,
        callback: data => {
          // if (!data) return;
          this.getTrailUpdateList({ orderNo });
          showTipsFun(false);
        },
      });
    });
  };

  render() {
    const { form, loading, trailUpdateList, onSelectRow, selectedRows } = this.props;
    const { visibleFile, showTips, orderNum } = this.state;
    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const data = trailUpdateList[orderNum] || {};

    return (
      <Fragment>
        <div className={styles.customPartsOfferInfo}>
          <AntdForm>
            <StandardTable
              loading={loading}
              data={data}
              columns={this.columns}
              selectedRows={selectedRows}
              onPaginationChange={this.handleStandardTableChange}
              className={this.className}
              // code={codes.page}
              expandForm={false}
              scrollX={1150}
              canInput={true}
              onSelectRow={selectedRows => {
                onSelectRow(selectedRows);
              }}
            />
          </AntdForm>
          {orderNum && (
            <div className={styles.page_bottom_btn}>
              <AdButton
                code={codes.save}
                text="保存"
                type="primary"
                onClick={() => this.saveData()}
              ></AdButton>
            </div>
          )}
        </div>
      </Fragment>
    );
  }
}
